package com.jthinker.web.controller.front;

import com.jthinker.bean.vo.Constant;
import com.jthinker.bean.vo.UserInfo;
import com.jthinker.service.UserService;
import com.jthinker.utils.RSAUtils;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.security.MessageDigest;

/**
 * Created by chen.gang on 15-2-20.
 */
@Controller
public class LoginController
{
    @Resource
    private UserService userService;

    @RequestMapping(Constant.URL_LOGIN)
    public String view()
    {
        return "login/login";
    }

    @RequestMapping("/doLogin")
    public ModelAndView doLogin(@RequestParam(required = false) String username, @RequestParam(required = false) String password, HttpSession session)
    {
        ModelAndView mv = new ModelAndView();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password))
        {
            mv.setViewName("login/login");
            mv.addObject("error", "用户名或密码不能为空!");
            return mv;
        }

        //原密码
        password = RSAUtils.decryptStringByJs(password);
        String saltPassword = getSaltPassword(password, username);

        UserInfo info = userService.login(username, saltPassword);
        if (info == null)
        {
            mv.setViewName("login/login");
            mv.addObject("error", "用户名或密码错误!");
            return mv;
        }

        session.setAttribute(Constant.SESSION_USER, info);
        mv.setViewName("redirect:/index");
        return mv;
    }

    @RequestMapping("/doLogout")
    public String doLogout(HttpSession session)
    {
        session.removeAttribute(Constant.SESSION_USER);
        session.invalidate();
        return "redirect:/index";
    }

    public static String getSaltPassword(String pass, String salt)
    {
        StringBuilder sb = new StringBuilder();
        sb.append(pass).append("{").append(salt).append("}");
        return encodeByMD5(sb.toString());
    }

    public static String encodeByMD5(String str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(str.getBytes());
            return Hex.encodeHexString(messageDigest.digest());
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }

}
